package com.zzyk.main.configuration.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.zzyk.main.model.vo.Message;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Ajax请求处理 用于前后台分离的场景
 */
public class GenericFilter extends UserFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("ContentType", "text/html;charset=UTF-8");

        String requestedWith = req.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestedWith)) {
            Message message = new Message();
            if(SecurityUtils.getSubject().isAuthenticated()){
                message.setCode(403);
                message.setMessage("无权操作");
            }else{
                message.setCode(401);
                message.setMessage("请登录后操作");
            }
            resp.getWriter().write(JSON.toJSONString(message));
        } else {
            if(SecurityUtils.getSubject().isAuthenticated()){
                Message message = new Message();
                message.setCode(403);
                message.setMessage("无权操作");
                resp.getWriter().write(JSON.toJSONString(message));
            }else{
                this.saveRequestAndRedirectToLogin(request, response);
            }
        }
        return false;
    }
}
